// 账户体系模块-mysql服务处理

// 引入数据库模块
const db = require('../../config/mysql.js')
const utils = require("../../common/utils")
const bcrypt = require('bcryptjs')
// 引入jwt
const jwt = require('jsonwebtoken')
const secretKey = 'ethink'    // 密钥
// 引入配置
const host = require("../../config/host.js")
const axios = require("axios")

// 注册
const register = (email, password) => {
  let uuid = utils.generateId()
  let key = utils.generateKey()
  let secret = utils.generateSecret()
  let register_time = utils.formatDate(new Date().getTime())
  return new Promise((resolve, reject) => {
    db.query(`select email from sys_user where email = "${email}"`, (err, result) => {
      if (err) return reject(err)
      if (result.length >= 1) return resolve("邮箱已被注册")
      // 邮箱不存在
      password = bcrypt.hashSync(password, 10)
      let sql = `insert into sys_user (id, nickName, email, password, keyId, secretKey, register_time) values("${uuid}","${email}","${email}","${password}","${key}","${secret}","${register_time}")`
      db.query(sql, (err1, res) => {
        if (err1) return reject(err1)
        if (res.affectedRows == 1) return resolve("注册成功")
      })
    })
  })
}

// 登录
const login = (email, password) => {
  return new Promise((resolve, reject) => {
    db.query(`select * from sys_user where email = "${email}"`, (err, result) => {
      if (err) return reject(err)
      if (result.length == 0) return reject("邮箱不存在，请先注册")
      if (result.length == 1) {
        // 密码比对
        let compareResult = bcrypt.compareSync(password, result[0].password)
        if (!compareResult) return reject('密码错误，请重新输入')
        // 是否被禁用
        if (result[0].status) {
          // token生成
          db.query(`select * from sys_role where id = "${result[0].role_id}"`, (err1, result1) => {
            if (err1) return reject(err1)
            if (result1.length == 1) {
              const userInfo = { ...result[0] }
              userInfo.role_name = result1[0].role_name
              delete userInfo.password
              delete userInfo.status
              let token = jwt.sign(userInfo, secretKey, { expiresIn: '7d' })
              return resolve({
                token: 'Bearer ' + token,
                indexPath: result1[0].index_page,
                sysTitle: result1[0].sys_title
              })
            }
            return reject('登录失败')
          })
        } else {
          return reject('该用户已被禁用，请联系管理员')
        }
      }
    })
  })
}

// 微信登录
const wxLogin = (code, encryptedData, iv) => {
  return new Promise((resolve, reject) => {
    let appid = host.appid
    let secret = host.secret
    let js_code = code
    let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${js_code}&grant_type=authorization_code`

    axios.get(url).then(res => {
      let { openid, session_key } = res.data
      // 查询是否已经注册，未注册注册，注册返回用户信息
      db.query(`select * from wx_user where openid = "${openid}"`, (err, result) => {
        if (err) return reject(err)
        // 已经注册过的，直接获取用户信息并返回
        if (result.length == 1) {
          const userInfo = { ...result[0] }
          let token = jwt.sign(userInfo, secretKey, { expiresIn: '7d' })
          return resolve({
            userInfo: { ...userInfo },
            token: 'Bearer ' + token
          })
        } else {
          // 注册
          let register_time = utils.formatDate(new Date().getTime())
          let sql = `insert into wx_user (openid, nickName, register_time) values("${openid}", "微信用户", "${register_time}")`
          db.query(sql, (err1, res) => {
            if (err1) return reject(err1)
            if (res.affectedRows == 1) {
              db.query(`select * from wx_user where openid = "${openid}"`, (err, result) => {
                if (err) return reject(err)
                if (result.length == 1) {
                  const userInfo = { ...result[0] }
                  let token = jwt.sign(userInfo, secretKey, { expiresIn: '7d' })
                  return resolve({
                    userInfo: { ...userInfo },
                    token: 'Bearer ' + token
                  })
                }
              })
            }
          })
        }
      })
    }).catch(error => {
      return reject('登录失败')
    })
  })
}


module.exports = {
  register,
  login,
  wxLogin
}